package com.ray.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.junit.experimental.theories.FromDataPoints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONArray;
import com.ray.bean.AdvancePurchaseBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialCountBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.FeedUseMaterialCountBean;
import com.ray.bean.MaterialPositionBean;
import com.ray.bean.OrderInfoDetailSourceAndApplyBean;
import com.ray.bean.OrderReceiveViewBean;
import com.ray.bean.PurchaseDetailBean;
import com.ray.bean.PurchaseOrderBean;
import com.ray.bean.PurchaseOrderDetailBean;
import com.ray.bean.PurchasePrintBean;
import com.ray.bean.ReportBean;
import com.ray.bean.UserBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.AdvancePurchaseMapepr;
import com.ray.mapper.ApprovalMapper;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.FeedUseMaterialCountMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.OtherWarehouseMapper;
import com.ray.mapper.PurchaseOrderMapper;
import com.ray.mapper.ShoppingMallMapper;
import com.ray.pojo.AvailableCountPojo;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;

import net.sf.json.JSONObject;

/**
 * 采购单业务层
* <p>Title: purchaseOrderService</p>  
* <p>Description: </p>  
* @author 李斌  
* @date 2018年9月13日
 */
@Service 
public class PurchaseOrderService {
	
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	AdvancePurchaseMapepr advancePurchaseMapepr;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	FeedUseMaterialCountMapper feedUseMaterialCountMapper;
	@Autowired
	PurchaseOrderMapper purchaseOrderMapper;
	@Autowired
	ApprovalMapper approvalMapper;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	OtherWarehouseMapper otherWarehouseMapper;
	@Autowired
	ShoppingMallMapper shoppingMallMapper;
	
	@Autowired
	OrderService orderService;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	UserService userService;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	CompanyEmailService companyEmailService;
	@Autowired
	CompanyMaterialCountService companyMaterialCountService;
	
	@Autowired
	IssueNoteService issueNoteService;
	
	@Autowired
	FeedOrderService feedOrderService;
	/**
	 * @throws ParseException 
	 * 保存订单采购单
	* @date 2018年9月13日 上午9:07:57 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String savePurchaseOrder(Map<String, Object> map) throws ParseException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String date=sdf.format(new Date());
		List<CompanyMaterialTableBean> companyMaterialTableBeans = new ArrayList<CompanyMaterialTableBean>();
		Map<String,Object> feedDetailMap = new HashMap<String,Object>();
		List<String> mainList = new ArrayList<String>();
		Map<String,Object> returnFeedOrderOutCountMap = new HashMap<String,Object>();
		//类型map 
		Map<String,Class> classMap=new HashMap<String,Class>();
		classMap.put("detailList", PurchaseDetailBean.class);
		classMap.put("feedDetailList", PurchaseOrderDetailBean.class);
		String beanStr=map.get("purchase").toString();
		JSONObject jsonObject=JSONObject.fromObject(beanStr);
		PurchaseOrderBean purchaseOrderBean=(PurchaseOrderBean) JSONObject.toBean(jsonObject, PurchaseOrderBean.class,classMap);
		String cgId = dingTalkMapper.getApprovalNo("CG");
		mainList.add(cgId);
		//重构后的插入对象
		List<PurchaseOrderBean> purchaseOrderBeanList = new ArrayList<PurchaseOrderBean>();
		for(PurchaseDetailBean purchaseDetailBean:purchaseOrderBean.getDetailList()) {
			Map<String,Object> companyMaterialParam = new HashMap<String,Object> ();
			//查询公司物料
			companyMaterialParam.put("materialCode", purchaseDetailBean.getMaterialCode());		
			companyMaterialParam.put("loginCompany", map.get("loginCompany"));
			CompanyMaterialTableBean companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(companyMaterialParam);
			//校验物料
			Integer num = isCheckMateiral(companyMaterialTableBean);
			companyMaterialTableBeans.add(companyMaterialTableBean);
			//校验物料是否有出入库记录未审核  
			map.put("materialCode", purchaseDetailBean.getMaterialCode());
			orderService.getWarehouseInOutByMateiralOnNotStatus(map);
			for(PurchaseOrderDetailBean podb:purchaseDetailBean.getFeedDetailList()) {
				PurchaseOrderBean purchaseOrder = new PurchaseOrderBean();
				purchaseOrder.setId(cgId);
				purchaseOrder.setPurchaseDetailId(StringUtil.getUUID());
				purchaseOrder.setType(1);
				purchaseOrder.setMaterialCode(purchaseDetailBean.getMaterialCode());
				purchaseOrder.setMaterialFactory(podb.getMaterialFactory());
				purchaseOrder.setLineNo(podb.getLineNo());
				purchaseOrder.setMaterialType(podb.getMaterialType());
				purchaseOrder.setProviderName(purchaseOrderBean.getProviderName());
				if(purchaseOrderBean.getAgentSource().equals(2)) {
					purchaseOrder.setAgent(purchaseOrderBean.getAgent());
				}
				purchaseOrder.setModel(purchaseDetailBean.getModel());
				purchaseOrder.setMaterialName(purchaseDetailBean.getMaterialName());
				purchaseOrder.setColor(purchaseDetailBean.getColor());
				purchaseOrder.setInCount(0.0);
				purchaseOrder.setPurchaseCount(podb.getPurchaseCount());
				purchaseOrder.setIsFinish(0);
				purchaseOrder.setIsPrint(0);
				purchaseOrder.setStatus(0);
				purchaseOrder.setCompany(map.get("loginCompany").toString());
				purchaseOrder.setCreateUser(map.get("loginUserId").toString());
				purchaseOrder.setCreateTime(date);
				purchaseOrder.setCurrency(purchaseOrderBean.getCurrency());
				purchaseOrder.setTax(purchaseDetailBean.getTax());
				purchaseOrder.setPurchasePeople(purchaseOrderBean.getPurchasePeople());
				purchaseOrder.setPrice(purchaseDetailBean.getPrice());
				purchaseOrder.setFeedDetailId(podb.getFeedDetailId());
				purchaseOrder.setOrderId(podb.getOrderId());
				
				/**
				 * 查询预采购单 通过物料信息与订单信息
				 */
				Map<String,Object> advanceMap = new HashMap<String,Object>();
				advanceMap.put("materialName", purchaseOrder.getMaterialName());
				advanceMap.put("model", purchaseOrder.getModel());
				advanceMap.put("color", purchaseOrder.getColor());
				advanceMap.put("providerName", purchaseOrder.getProviderName());
				advanceMap.put("orderId", purchaseOrder.getOrderId());
				advanceMap.put("loginCompany", map.get("loginCompany"));
				List<AdvancePurchaseBean> advancePurchaseBeans = advancePurchaseMapepr.getAdvancePurchase(advanceMap);
				if(advancePurchaseBeans !=null && advancePurchaseBeans.size()>0) {
					AdvancePurchaseBean advancePurchaseBean = advancePurchaseBeans.get(0);
					purchaseOrder.setLaterPhaseOne(advancePurchaseBean.getLaterPhaseOne());
					purchaseOrder.setLaterPhaseTwo(advancePurchaseBean.getLaterPhaseTwo());
					purchaseOrder.setLaterPhaseThr(advancePurchaseBean.getLaterPhaseThr());
					purchaseOrder.setLaterPhaseFour(advancePurchaseBean.getLaterPhaseFour());
					advanceMap.put("mainId", advancePurchaseBean.getMainId());
					advancePurchaseMapepr.deleteAdvancePurchaseByMainId(advanceMap);
				}else { 
					purchaseOrder.setLaterPhaseOne(TimeAndUnix.plusDay(num,sdf.format(new Date()) ));
				}
				
				//插入投料单库存占用数
				feedDetailMap.put("loginCompany", map.get("loginCompany"));
				feedDetailMap.put("feedDetailId", purchaseOrder.getFeedDetailId());
				List<FeedOrderDetailBean> feedOrderDetailBeans = feedUseMaterialCountMapper.getFeedOrderDetailById(feedDetailMap);
				if(feedOrderDetailBeans==null || feedOrderDetailBeans.size()<1) {
					throw new ServiceException("未查到投料单明细异常");
				}
				BigDecimal purchaseCount = new BigDecimal(purchaseOrder.getPurchaseCount().toString());
				BigDecimal feedCount = new BigDecimal(feedOrderDetailBeans.get(0).getFeedCount().toString());
				//如果投料数大于采购数,说明这个投料单有占用了
				if(feedCount.subtract(purchaseCount).doubleValue()>0) {
					 /**
	   				  *	处理被退回投料单已领料的逻辑
	   				  *	李斌
	   				  */
					returnFeedOrderOutCountMap.put("orderId", purchaseOrder.getOrderId());
					returnFeedOrderOutCountMap.put("materialType", purchaseOrder.getMaterialType());
					returnFeedOrderOutCountMap.put("materialFactory", purchaseOrder.getMaterialFactory());
					returnFeedOrderOutCountMap.put("materialCode", purchaseDetailBean.getMaterialCode());
					returnFeedOrderOutCountMap.put("loginCompany",  map.get("loginCompany"));
					returnFeedOrderOutCountMap.put("lineNo", purchaseOrder.getLineNo());
					Double returnFeedOrderOutCount = orderService.getReturnFeedOrderOnOutWarehouseCount(returnFeedOrderOutCountMap);
					//判断退回的投料单是否有已经出库的
					if(returnFeedOrderOutCount.doubleValue()!=0) {
						//如果退回的数量小于投料数
						if(returnFeedOrderOutCount.doubleValue()<feedCount.doubleValue()) {
							List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedDetailMap);
							if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
								feedUseMaterialCountBeans.get(0).setFeedUseCount(feedCount.doubleValue()-returnFeedOrderOutCount.doubleValue());
								int feedUseProductionRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBeans.get(0));
								if(feedUseProductionRow<1) {
									throw new ServiceException("插入占用数量信息异常");
								}
							}else { 
								FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
								feedUseMaterialCountBean.setMaterialName(purchaseDetailBean.getMaterialName());
								feedUseMaterialCountBean.setModel(purchaseDetailBean.getModel());
								feedUseMaterialCountBean.setColor(purchaseDetailBean.getColor());
								feedUseMaterialCountBean.setProviderName(purchaseDetailBean.getProviderName());
								feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailBeans.get(0).getId());
								feedUseMaterialCountBean.setFeedUseCount(feedCount.doubleValue()-returnFeedOrderOutCount.doubleValue());
								feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
								int feedUseRow = feedUseMaterialCountMapper.insertFeedUseMaterialCount(feedUseMaterialCountBean);
								if(feedUseRow<1) {
									throw new ServiceException("插入占用数量信息异常");
								}
							}
						}
						List<FeedOrderDetailBean> feedList = new ArrayList<FeedOrderDetailBean>();
						FeedOrderDetailBean feedOrderDetailBean = feedOrderDetailBeans.get(0);
						/*if(feedOrderDetailBean.getFeedCount().doubleValue()<=returnFeedOrderOutCount.doubleValue()) {
							feedOrderDetailBean.setIsReceiveFinish(1);
							feedOrderDetailBean.setReceiveCount(feedOrderDetailBean.getFeedCount());
						}else {
							feedOrderDetailBean.setIsReceiveFinish(0);
							feedOrderDetailBean.setReceiveCount(returnFeedOrderOutCount);
						}*/
						feedList.add(feedOrderDetailBean);
						returnFeedOrderOutCountMap.put("feedList", feedList);
						companyMaterialMapper.updateFeedOrderDetailReceive(returnFeedOrderOutCountMap);
					}else {
						List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedDetailMap);
						if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
							feedUseMaterialCountBeans.get(0).setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
							int feedUseProductionRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBeans.get(0));
							if(feedUseProductionRow<1) {
								throw new ServiceException("插入占用数量信息异常");
							}
						}else { 
							FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
							feedUseMaterialCountBean.setMaterialName(purchaseDetailBean.getMaterialName());
							feedUseMaterialCountBean.setModel(purchaseDetailBean.getModel());
							feedUseMaterialCountBean.setColor(purchaseDetailBean.getColor());
							feedUseMaterialCountBean.setProviderName(purchaseDetailBean.getProviderName());
							feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailBeans.get(0).getId());
							feedUseMaterialCountBean.setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
							feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
							int feedUseRow = feedUseMaterialCountMapper.insertFeedUseMaterialCount(feedUseMaterialCountBean);
							if(feedUseRow<1) {
								throw new ServiceException("插入占用数量信息异常");
							}
						}
					}
				}
				Map<String,Object> feedMap= new HashMap<String,Object>();
				feedMap.put("isBuild", 1); 
				if(purchaseOrder.getFeedDetailId()!=null&&!purchaseOrder.getFeedDetailId().trim().equals("")) {
					PurchaseOrderBean checkPurchaseOrderBean = purchaseOrderMapper.getPurchaseOrderByFeedDetailId(feedDetailMap);
					Assert.isTrue(checkPurchaseOrderBean==null, "该订单已生成采购单,请勿重复生成");
					feedMap.put("feedDetailId", purchaseOrder.getFeedDetailId());
					int feedRow = feedUseMaterialCountMapper.setFeedDetailStatusOnIsBuild(feedMap);
					if(feedRow<1) { 
						throw new ServiceException("更新投料单状态异常");
					}
				}else {  
					throw new ServiceException("投料单明细id为空异常");
				}
				feedMap.clear();
				purchaseOrderBeanList.add(purchaseOrder);
			}
			
		}
		map.put("purchaseOrderBeanList", purchaseOrderBeanList);
		purchaseOrderMapper.savePurchaseOrder(map);
		/** 
		 * 发消息
		 */
		
		List<String> orderList = new ArrayList<String>();
		for(PurchaseOrderBean pojo:purchaseOrderBeanList) {
			orderList.add(pojo.getOrderId());
		} 
		map.put("orderList",orderList);
		List<String> factoryNoList =  orderMapper.getFactoryNoByOrderId(map);
		String bodyMessage = " 工厂型号 :";
		for(String factoryNo:factoryNoList) {
			bodyMessage+=factoryNo+",";
		}    
		String idString = mainList.toString().substring(1,mainList.toString().length()-1);
		String queryCondition = "#type=1&mainId="+idString.replace(" ","");  
		String msg = companyMaterialService.sendWechatMessage("采购单", 1, bodyMessage, sdf.format(new Date()), map, RedirectUrlUtil.queryPurchaseOrder+queryCondition, 0);
		Map<String,Object> sendMap = new HashMap<String,Object>();
		sendMap.put("loginCompany", map.get("loginCompany"));
		sendMap.put("companyMaterialTableBeanList", companyMaterialTableBeans);
		sendMap.put("purchaseOrderBeanList", purchaseOrderBeanList);
		sendMap.put("mainList", mainList);
		sendMap.put("date",date);
		this.getSendData(sendMap);
		return msg;
	}
	
	/**
	 * 从投料单直接生成采购单
	* @date 2018年9月14日 下午1:28:38 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String savePurchaseOrderOther(Map<String,Object> map,List<PurchaseOrderBean> purchaseOrderBeans) throws ParseException, ServiceException {
		List<String> mainList = new ArrayList<String>();
		List<CompanyMaterialTableBean> companyMaterialTableBeanList = new ArrayList<CompanyMaterialTableBean>();
		//保存采购单 
		Map<String,Object> purchaseMap = new HashMap<String,Object>();
		Map<String, Object> returnFeedOrderOutCountMap = new HashMap<String,Object>();
		List<PurchaseOrderBean> purchaseOrderBeanList = new ArrayList<PurchaseOrderBean>();
		List<PurchaseOrderBean> allPurchase = new ArrayList<PurchaseOrderBean>();
		//保存发送消息的set
		Set<String> orderIdSet = new HashSet<String>(); 
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String date = sdf.format(new Date());
		Map<String,Object> companyMaterialParam = new HashMap<String,Object>();
		Map<String,Object> feedDetailMap = new HashMap<String,Object>();
		Map<String,Object> advanceMap = new HashMap<String,Object>();
		if(purchaseOrderBeans!=null && purchaseOrderBeans.size()>0){
			for(PurchaseOrderBean purchaseOrderBean: purchaseOrderBeans) {
				String cgId = dingTalkMapper.getApprovalNo("CG");
				mainList.add(cgId);
				for(PurchaseDetailBean purchaseDetailBean:purchaseOrderBean.getDetailList()) {
					companyMaterialParam.clear();
					//查询公司物料
					companyMaterialParam.put("materialCode", purchaseDetailBean.getMaterialCode());		
					companyMaterialParam.put("loginCompany", map.get("loginCompany"));
					CompanyMaterialTableBean companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(companyMaterialParam);
					Integer num = isCheckMateiral(companyMaterialTableBean);
					companyMaterialTableBeanList.add(companyMaterialTableBean);
					//校验物料是否有出入库记录未审核
					orderService.getWarehouseInOutByMateiralOnNotStatus(companyMaterialParam);
					for(PurchaseOrderDetailBean purchaseOrderDetailBean:purchaseDetailBean.getFeedDetailList()) {
						PurchaseOrderBean purchaseOrder = new PurchaseOrderBean();
						purchaseOrder.setFeedDetailId(purchaseOrderDetailBean.getId());
						purchaseOrder.setId(cgId);
						purchaseOrder.setPurchaseDetailId(StringUtil.getUUID());
						purchaseOrder.setType(1);
						purchaseOrder.setStatus(0);
						purchaseOrder.setInCount(0.0);
						purchaseOrder.setIsFinish(0);
						purchaseOrder.setPurchasePeople(map.get("loginUserId").toString());
						purchaseOrder.setMaterialCode(purchaseDetailBean.getMaterialCode());
						purchaseOrder.setMaterialName(companyMaterialTableBean.getMaterialName());
						purchaseOrder.setModel(companyMaterialTableBean.getModel());
						purchaseOrder.setColor(companyMaterialTableBean.getColor());
						purchaseOrder.setProviderName(purchaseOrderBean.getProviderName());
						if(purchaseOrderDetailBean.getAgent()!=0) {
							purchaseOrder.setAgent(purchaseOrderDetailBean.getAgent());
						}
						purchaseOrder.setCurrency("人民币");
						purchaseOrder.setIsPrint(0);
						purchaseOrder.setLineNo(purchaseOrderDetailBean.getLineNo());
						purchaseOrder.setMaterialType(purchaseOrderDetailBean.getMaterialType());
						purchaseOrder.setMaterialFactory(purchaseOrderDetailBean.getMaterialFactory());
						purchaseOrder.setPurchaseCount(purchaseOrderDetailBean.getPurchaseCount());
						purchaseOrder.setOrderId(purchaseOrderDetailBean.getOrderId());
						purchaseOrder.setPrice(purchaseDetailBean.getPrice());
						purchaseOrder.setTax(purchaseDetailBean.getTax());
						purchaseOrder.setCreateTime(date);
						purchaseOrder.setCreateUser(map.get("loginUserId").toString());
						purchaseOrder.setCompany(map.get("loginCompany").toString());
						//查询预采购单
						advanceMap.clear(); 
						advanceMap.put("materialName", purchaseOrder.getMaterialName());
						advanceMap.put("model", purchaseOrder.getModel());
						advanceMap.put("color", purchaseOrder.getColor());
						advanceMap.put("providerName", purchaseOrder.getProviderName());
						advanceMap.put("orderId", purchaseOrder.getOrderId());
						advanceMap.put("loginCompany", map.get("loginCompany"));
						List<AdvancePurchaseBean> advancePurchaseBeans = advancePurchaseMapepr.getAdvancePurchase(advanceMap);
						if(advancePurchaseBeans !=null && advancePurchaseBeans.size()>0) {
							AdvancePurchaseBean advancePurchaseBean = advancePurchaseBeans.get(0);
							purchaseOrder.setLaterPhaseOne(advancePurchaseBean.getLaterPhaseOne());
							purchaseOrder.setLaterPhaseTwo(advancePurchaseBean.getLaterPhaseTwo());
							purchaseOrder.setLaterPhaseThr(advancePurchaseBean.getLaterPhaseThr());
							purchaseOrder.setLaterPhaseFour(advancePurchaseBean.getLaterPhaseFour());
							advanceMap.put("mainId", advancePurchaseBean.getMainId());
							advancePurchaseMapepr.deleteAdvancePurchaseByMainId(advanceMap);
						}else { 
							purchaseOrder.setLaterPhaseOne(TimeAndUnix.plusDay(num,sdf.format(new Date()) ));
						}
						orderIdSet.add(purchaseOrder.getOrderId());
						//插入投料单库存占用数
						feedDetailMap.clear();
						feedDetailMap.put("loginCompany", map.get("loginCompany"));
						feedDetailMap.put("feedDetailId", purchaseOrder.getFeedDetailId());
						PurchaseOrderBean checkPurchaseOrderBean = purchaseOrderMapper.getPurchaseOrderByFeedDetailId(feedDetailMap);
						Assert.isTrue(checkPurchaseOrderBean==null, "该订单已生成采购单,请勿重复生成");
						List<FeedOrderDetailBean> feedOrderDetailBeans = feedUseMaterialCountMapper.getFeedOrderDetailById(feedDetailMap);
						if(feedOrderDetailBeans==null||feedOrderDetailBeans.size()<1) {
							throw new ServiceException("查询投料单明细异常");
						}  
						BigDecimal purchaseCount = new BigDecimal(purchaseOrder.getPurchaseCount().toString());
						BigDecimal feedCount = new BigDecimal(feedOrderDetailBeans.get(0).getFeedCount().toString());
						//如果投料数大于采购数,说明这个投料单有占用了 
						if(feedCount.subtract(purchaseCount).doubleValue()>0) {
							 /**
			   				  *	处理被退回投料单已领料的逻辑
			   				  *	李斌
			   				  */
							returnFeedOrderOutCountMap.put("orderId", purchaseOrderDetailBean.getOrderId());
							returnFeedOrderOutCountMap.put("materialType", purchaseOrderDetailBean.getMaterialType());
							returnFeedOrderOutCountMap.put("materialFactory", purchaseOrderDetailBean.getMaterialFactory());
							returnFeedOrderOutCountMap.put("materialCode", purchaseDetailBean.getMaterialCode());
							returnFeedOrderOutCountMap.put("loginCompany",  map.get("loginCompany"));
							returnFeedOrderOutCountMap.put("lineNo", purchaseOrderDetailBean.getLineNo());
							Double returnFeedOrderOutCount = orderService.getReturnFeedOrderOnOutWarehouseCount(returnFeedOrderOutCountMap);
							//判断退回的投料单是否有已经出库的
							if(returnFeedOrderOutCount.doubleValue()!=0) {
								//如果退回的数量小于投料数
								if(returnFeedOrderOutCount.doubleValue()<feedCount.doubleValue()) {
									List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedDetailMap);
									if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
										feedUseMaterialCountBeans.get(0).setFeedUseCount(feedCount.doubleValue()-returnFeedOrderOutCount.doubleValue());
										int feedUseProductionRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBeans.get(0));
										if(feedUseProductionRow<1) {
											throw new ServiceException("插入占用数量信息异常");
										}
									}else { 
										FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
										feedUseMaterialCountBean.setMaterialName(purchaseOrder.getMaterialName());
										feedUseMaterialCountBean.setModel(purchaseOrder.getModel());
										feedUseMaterialCountBean.setColor(purchaseOrder.getColor());
										feedUseMaterialCountBean.setProviderName(purchaseOrder.getProviderName());
										feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailBeans.get(0).getId());
										feedUseMaterialCountBean.setFeedUseCount(feedCount.doubleValue()-returnFeedOrderOutCount.doubleValue());
										feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
										int feedUseRow = feedUseMaterialCountMapper.insertFeedUseMaterialCount(feedUseMaterialCountBean);
										if(feedUseRow<1) {
											throw new ServiceException("插入占用数量信息异常");
										}
									}
								}
								List<FeedOrderDetailBean> feedList = new ArrayList<FeedOrderDetailBean>();
								FeedOrderDetailBean feedOrderDetailBean = feedOrderDetailBeans.get(0);
								/*if(feedOrderDetailBean.getFeedCount().doubleValue()<=returnFeedOrderOutCount.doubleValue()) {
									feedOrderDetailBean.setIsReceiveFinish(1);
									feedOrderDetailBean.setReceiveCount(feedOrderDetailBean.getFeedCount());
								}else {
									feedOrderDetailBean.setIsReceiveFinish(0);
									feedOrderDetailBean.setReceiveCount(returnFeedOrderOutCount);
								}*/
								feedList.add(feedOrderDetailBean);
								returnFeedOrderOutCountMap.put("feedList", feedList);
								companyMaterialMapper.updateFeedOrderDetailReceive(returnFeedOrderOutCountMap);
							}else {
								List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedDetailMap);
								if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
									feedUseMaterialCountBeans.get(0).setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
									int feedUseProductionRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBeans.get(0));
									if(feedUseProductionRow<1) {
										throw new ServiceException("插入占用数量信息异常");
									}
								}else { 
									FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
									feedUseMaterialCountBean.setMaterialName(purchaseDetailBean.getMaterialName());
									feedUseMaterialCountBean.setModel(purchaseDetailBean.getModel());
									feedUseMaterialCountBean.setColor(purchaseDetailBean.getColor());
									feedUseMaterialCountBean.setProviderName(purchaseDetailBean.getProviderName());
									feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailBeans.get(0).getId());
									feedUseMaterialCountBean.setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
									feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
									int feedUseRow = feedUseMaterialCountMapper.insertFeedUseMaterialCount(feedUseMaterialCountBean);
									if(feedUseRow<1) {
										throw new ServiceException("插入占用数量信息异常");
									}
								}
							}
							/*List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedDetailMap);
							if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
								feedUseMaterialCountBeans.get(0).setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
								int feedUseProductionRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBeans.get(0));
								Assert.isTrue(feedUseProductionRow>0, "插入占用数量信息异常");
							}else { 
								FeedUseMaterialCountBean feedUseMaterialCountBean = new FeedUseMaterialCountBean();
								feedUseMaterialCountBean.setMaterialName(purchaseOrder.getMaterialName());
								feedUseMaterialCountBean.setModel(purchaseOrder.getModel());
								feedUseMaterialCountBean.setColor(purchaseOrder.getColor());
								feedUseMaterialCountBean.setProviderName(purchaseOrder.getProviderName());
								feedUseMaterialCountBean.setFeedDetailId(feedOrderDetailBeans.get(0).getId());
								feedUseMaterialCountBean.setFeedUseCount(feedCount.subtract(purchaseCount).doubleValue());
								feedUseMaterialCountBean.setCompany(map.get("loginCompany").toString());
								int feedUseRow = feedUseMaterialCountMapper.insertFeedUseMaterialCount(feedUseMaterialCountBean);
								Assert.isTrue(feedUseRow>0, "插入占用数量信息异常");
							}*/
						}
						Map<String,Object> feedMap= new HashMap<String,Object>();
						feedMap.put("loginCompany", map.get("loginCompany"));
						feedMap.put("feedDetailId", purchaseOrder.getFeedDetailId());
						feedMap.put("isBuild", 1);
						int feedRow = feedUseMaterialCountMapper.setFeedDetailStatusOnIsBuild(feedMap);
						Assert.isTrue(feedRow>0, "更新投料单状态异常");
						feedMap.clear();
						purchaseOrderBeanList.add(purchaseOrder);
						//用于发消息
						allPurchase.add(purchaseOrder);
					}
				}
				purchaseMap.put("purchaseOrderBeanList", purchaseOrderBeanList);
				purchaseOrderMapper.savePurchaseOrder(purchaseMap);
				purchaseMap.clear();
				purchaseOrderBeanList.clear();
			}
		}
		//发消息
		StringBuffer sb = new StringBuffer();
		map.put("orderList", new ArrayList<>(orderIdSet));
		//订单集合
		List<String> factoryNoList = orderMapper.getFactoryNoByOrderId(map);
		for(String factoryNo:factoryNoList) {
			sb.append(factoryNo+",");
		}
		String idString = mainList.toString().substring(1,mainList.toString().length()-1);
		String queryCondition = "#type=1&mainId="+idString.replace(" ","");    
		String message = companyMaterialService.sendWechatMessage("采购单待审核", 1, "订单采购单待审核 工厂型号:"+sb.toString(), date, map, RedirectUrlUtil.queryPurchaseOrder+queryCondition, 0);
		Map<String,Object> sendMap = new HashMap<String,Object>();
		sendMap.put("loginCompany", map.get("loginCompany"));
		sendMap.put("companyMaterialTableBeanList", companyMaterialTableBeanList);
		sendMap.put("purchaseOrderBeanList", allPurchase);
		sendMap.put("mainList", mainList);
		sendMap.put("date",date);
		this.getSendData(sendMap);;
		return message;
	}
	
	/**
	 * @throws ParseException 
	 * 保存库存采购单
	* @date 2018年9月13日 上午11:35:07 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public String savePurchaseStack(Map<String, Object> map) throws ParseException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String date=sdf.format(new Date());
		CompanyBean companyBean = companyMapper.getCompany(map);
		//类型map
		Map<String,Class> classMap=new HashMap<String,Class>();
		classMap.put("detailList", PurchaseDetailBean.class);
		String beanStr=map.get("purchase").toString();
		//多条
		JSONArray jsonArr = com.alibaba.fastjson.JSONObject.parseArray(beanStr);
		String returnMsg = "";
		for(int i=0;i<jsonArr.size();i++) {
			JSONObject jsonObject=JSONObject.fromObject(jsonArr.get(i).toString());
			PurchaseOrderBean purchaseOrderBean=(PurchaseOrderBean) JSONObject.toBean(jsonObject, PurchaseOrderBean.class,classMap);
			String cgId = dingTalkMapper.getApprovalNo("CG");
			//重构后保存的purchaseOrderBeanList
			List<PurchaseOrderBean> purchaseOrderBeanList = new ArrayList<PurchaseOrderBean>();
			Map<String,Object> companyMaterialParam = new HashMap<String,Object> ();
			for(PurchaseDetailBean purchaseDetailBean:purchaseOrderBean.getDetailList()) {
				//查询公司物料
				companyMaterialParam.clear();
				companyMaterialParam.put("materialCode", purchaseDetailBean.getMaterialCode());		
				companyMaterialParam.put("loginCompany", map.get("loginCompany"));
				CompanyMaterialTableBean companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(companyMaterialParam);
				if(companyBean.getIsNeedApprovalByMaterial()==1) {
					Assert.isTrue(companyMaterialTableBean.getPurchaseApproval().equals(1), "物料名称:"+companyMaterialTableBean.getMaterialName()+" 色号:"+companyMaterialTableBean.getColor()+"还未审核,请先审核物料");
				}
				Integer num = this.isCheckMateiral(companyMaterialTableBean);
				PurchaseOrderBean purchaseOrder = new PurchaseOrderBean();
				purchaseOrder.setId(cgId);
				purchaseOrder.setPurchaseDetailId(StringUtil.getUUID());
				purchaseOrder.setType(2);
				purchaseOrder.setMaterialCode(purchaseDetailBean.getMaterialCode());
				purchaseOrder.setMaterialName(purchaseDetailBean.getMaterialName());
				purchaseOrder.setModel(purchaseDetailBean.getModel());
				purchaseOrder.setColor(purchaseDetailBean.getColor());
				purchaseOrder.setProviderName(purchaseOrderBean.getProviderName());
				purchaseOrder.setPurchaseCount(purchaseDetailBean.getPurchaseCount());
				purchaseOrder.setPrice(purchaseDetailBean.getPrice());
				purchaseOrder.setTax(purchaseDetailBean.getTax());
				purchaseOrder.setCurrency(purchaseOrderBean.getCurrency());
				purchaseOrder.setPurchasePeople(purchaseOrderBean.getPurchasePeople());
				purchaseOrder.setMaterialType(companyMaterialTableBean.getMaterialType());
				purchaseOrder.setStatus(0);
				purchaseOrder.setCreateTime(date); 
				purchaseOrder.setCreateUser(map.get("loginUserId").toString());
				purchaseOrder.setIsFinish(0);
				purchaseOrder.setInCount(0.0); 
				purchaseOrder.setIsPrint(0);
				purchaseOrder.setProviderName(purchaseOrderBean.getProviderName());
				purchaseOrder.setLaterPhaseOne(TimeAndUnix.plusDay(num,sdf.format(new Date()) ));
				purchaseOrder.setCompany(map.get("loginCompany").toString());
				//客户订单编号
				purchaseOrder.setCustomerOrderId(purchaseDetailBean.getCustomerOrderId());
				//工厂型号
				purchaseOrder.setFactoryId(purchaseDetailBean.getFactoryId());
				//客户编号
				purchaseOrder.setCustomerId(purchaseDetailBean.getCustomerId());
				//说明
				purchaseOrder.setRemark(purchaseDetailBean.getRemark());
				if(purchaseOrderBean.getAgentSource().equals(2)) {
					purchaseOrder.setAgent(purchaseOrderBean.getAgent());
				}
				purchaseOrderBeanList.add(purchaseOrder);
			} 
			Map<String,Object> purchaseMap = new HashMap<String,Object>();
			purchaseMap.put("purchaseOrderBeanList", purchaseOrderBeanList);
			purchaseOrderMapper.savePurchaseOrder(purchaseMap);
			String bodyMessage = "采购Id :"+cgId;    
			String queryCondition = "#type=2&mainId="+cgId;    
			returnMsg+=companyMaterialService.sendWechatMessage("采购单", 1, bodyMessage, sdf.format(new Date()), map, RedirectUrlUtil.queryPurchaseOrder+queryCondition, 0)+"\r\n";
			//可以审核过账
			if("1".equals(map.get("selfApproval"))) {
				for(PurchaseOrderBean bean:purchaseOrderBeanList) {
					Map<String, String> approveMap = new HashMap<>();
					approveMap.put("type", "2");//库存采购
					approveMap.put("name",map.get("loginUserName").toString());//采购员
					approveMap.put("loginCompany", map.get("loginCompany").toString());
					approveMap.put("loginUserId", map.get("loginUserId").toString());
					approveMap.put("loginUserName", map.get("loginUserName").toString());
					approveMap.put("purchaseDetailId", bean.getPurchaseDetailId());
					approveMap.put("status", "1");
					this.approvalPurchaseOrder(approveMap,1);
				}
			}
		}
		return returnMsg;
	}
	
	
	


	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderList(Map<String, Object> map) {
		//判断是否分页 
		Object page = map.get("currentPage");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
		if(map.get("startTime")!=null) {
			Long startTime = Long.parseLong(map.get("startTime").toString());
			map.put("startTime", sdf.format(new Date(startTime)));
		}
		if(map.get("endTime")!=null) {
			Long endTime = Long.parseLong(map.get("endTime").toString());
			map.put("endTime", sdf.format(new Date(endTime)));
		}
		if(page==null) {//打印查询
			return this.getPurchaseOrderByPrint(map);
		}else {//列表查询
			return this.getPurchaseOrderByPage(map);
		}
	}
	
	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderForBackList(Map<String, Object> map) {
		int count = purchaseOrderMapper.getPurchaseOrderForBackCount(map);
		List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderForBackData(map);
		DatatablesViewPageBean<PurchaseOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<PurchaseOrderDetailPojo>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(pojos);
		return datatablesViewPageBean;
	}
	/**
	 * 分页查询采购单
	* @date 2018年9月13日 下午1:50:40 
	* @author 李斌
	* @return DatatablesViewPageBean<PurchaseOrderDetailPojo> 
	* @throws
	 */
	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderByPage(Map<String,Object> map){
		Map<String,Object> approvalParam = new HashMap<String,Object>();
		approvalParam.put("type","4"); 
		approvalParam.put("id",map.get("loginUserId"));  
		approvalParam.put("loginCompany", map.get("loginCompany"));
		//获取当前登录人可以审核的人员
		List<String> userIds = approvalMapper.getHaveId(approvalParam);
		if(map.get("currentPage")!=null) {
			Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
			int pageSize = Integer.parseInt(map.get("pageSize").toString());
			Integer start = (currentPage-1)*pageSize;
			map.put("start", start); 
			map.put("length", pageSize);
		}
		if(map.get("ptId") !=null) {
			List<String> ids =  this.getPurchaseDetailIdByPtId(map);
			if(ids !=null && ids.size()>0) {
				map.put("ids", ids.toArray(new String [ids.size()]));
			}
		}
		//公司设定
		CompanyBean companyBean = companyMapper.getCompany(map);
		
		List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
		map.put("nopage", "nopage");
		int count = purchaseOrderMapper.getPurchaseOrderByPageCount(map);
		//所有客户 
		map.remove("type");
		List<CustomerBean> customerBeans = basicDataMapper.queryCustomers(map);
		for(PurchaseOrderDetailPojo pojo:pojos) {
			pojo.setIsShowYltsTotalOnPurchase(companyBean.getIsShowYltsTotalOnPurchase());
			for(CustomerBean customerBean:customerBeans) {
				if(pojo.getProviderName().equals(customerBean.getCustomerName())) {
					pojo.setCustomerBean(customerBean);
					break;
				}
			}	
			for(String userId:userIds) {
				if(userId.equals(pojo.getCreateUserId())) {
					pojo.setIsApprovalUser(1);
					break; 
				}
			}
			if(pojo.getStatus().equals(0)) {
				approvalParam.put("loginUserId", pojo.getCreateUserId());
				List<String> approvalUserList = approvalMapper.getApprovalUserBeanByLoginUserId(approvalParam);
				pojo.setAuditableUser((String[])approvalUserList.toArray(new String[approvalUserList.size()]));
				pojo.setPrintNeetApproval(companyBean.getPurchasePrintIsNeetApproval());
			}
		} 
		DatatablesViewPageBean<PurchaseOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<PurchaseOrderDetailPojo>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(pojos);
		return datatablesViewPageBean;
	}
	
	/**
	 * 通过商城获取采购单信息
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderByPageFromShoppingCall(Map<String,Object> map){
		List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
		map.put("nopage", "nopage");
		int count = purchaseOrderMapper.getPurchaseOrderByPageCount(map);
		DatatablesViewPageBean<PurchaseOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<PurchaseOrderDetailPojo>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(pojos);
		return datatablesViewPageBean;
	}
	
	
	
	
	
	/**
	 * 打印查询采购单
	* @date 2018年9月13日 下午1:52:27 
	* @author 李斌
	* @return DatatablesViewPageBean<PurchaseOrderDetailPojo> 
	* @throws
	 */
	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderByPrint(Map<String,Object> map){
		if(map.get("orderIds")==null) {
			throw new ServiceException("参数不全异常");
		} 
		if(map.get("type")==null) {
			throw new ServiceException("采购类型为空异常");
		}
		DatatablesViewPageBean<PurchaseOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<PurchaseOrderDetailPojo>();
		String idsStr = map.get("orderIds").toString();
		String[] ids = idsStr.split(",");
		map.put("ids", ids);
		//公司设定 
		CompanyBean companyBean = companyMapper.getCompany(map);
		map.put("neetApproval", companyBean.getPurchasePrintIsNeetApproval());
		List<PurchaseOrderDetailPojo> purchaseOrderDetailPojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
		if("1".equals(map.get("type").toString())) {
			List<PurchaseOrderDetailPojo> groupList = new ArrayList<PurchaseOrderDetailPojo>();
			for(PurchaseOrderDetailPojo pojo:purchaseOrderDetailPojos) {
				PurchaseOrderDetailPojo purchaseOrderDetailPojo = new PurchaseOrderDetailPojo();
				purchaseOrderDetailPojo.setMaterialCode(pojo.getMaterialCode());
				purchaseOrderDetailPojo.setOrderId(pojo.getOrderId());
				purchaseOrderDetailPojo.setPurchaseDetailId(pojo.getPurchaseDetailId());
				groupList.add(purchaseOrderDetailPojo);
			} 
			map.put("groupList", groupList); 
			purchaseOrderDetailPojos = purchaseOrderMapper.getAleradyPurchaseOrderByOrderAndMateiral(map);
			datatablesViewPageBean.setReturnData(purchaseOrderDetailPojos);
		}else {
			datatablesViewPageBean.setReturnData(purchaseOrderDetailPojos);
		}
		//所有客户 
		map.remove("type"); 
		Set<String> providerNameSet = new HashSet<String>();
		List<CustomerBean> customerBeans = basicDataMapper.queryCustomers(map);
		for(PurchaseOrderDetailPojo purchaseOrderDetailPojo:datatablesViewPageBean.getReturnData()) {
			for(CustomerBean customerBean:customerBeans) {
				if(purchaseOrderDetailPojo.getProviderName().equals(customerBean.getCustomerName())) {
					purchaseOrderDetailPojo.setCustomerBean(customerBean);
					providerNameSet.add(customerBean.getCustomerName());
					break;
				}
			}	
			/**
			 * 没有在本公司并且有agent则认为是来自于商城
			 * 20190413 ssg
			 */
			if(purchaseOrderDetailPojo.getAgent()!=0) {
				CompanyBean companyBeanFromShop = shoppingMallMapper.getCompanyManagerUser(purchaseOrderDetailPojo.getProviderName());
				CustomerBean customerBean = new CustomerBean();
				customerBean.setId(purchaseOrderDetailPojo.getAgent()+"");//经销商id
				customerBean.setFax(companyBeanFromShop.getFax());//传真
				customerBean.setEmail(companyBeanFromShop.getEmail());//邮件
				customerBean.setPhone(companyBeanFromShop.getPhone());//电话
				customerBean.setContact(companyBeanFromShop.getName());//联系人
				customerBean.setCustomerName(purchaseOrderDetailPojo.getProviderName());
				purchaseOrderDetailPojo.setCustomerBean(customerBean);
			}
		} 
		return datatablesViewPageBean;
	}

	/**
	 * 审批采购单
	* @date 2018年9月14日 上午8:54:42 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String approvalPurchaseOrder(Map<String, String> map,int status) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String type = map.get("type");
		if(type ==null) {
			throw new ServiceException("无采购单类型错误");
		} 
		map.put("approvalTime",simpleDateFormat.format(new Date())); 
		map.put("approvalUser",map.get("loginUserId"));
		UserBean userBean = userService.getUserByName(map);
		PurchaseOrderBean purchaseOrderBean = purchaseOrderMapper.getPurchaseOrderByPurchaseDetailId(map);
		Assert.notNull(purchaseOrderBean, "采购单为空异常");
		Map<String,Object> approvalParam = new HashMap<String,Object>();
		approvalParam.put("type","4"); 
		approvalParam.put("loginUserId", map.get("loginUserId"));
		approvalParam.put("loginCompany", map.get("loginCompany"));
		List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
		int isStatus = 0;
		if(userIds!=null&&userIds.size()>0) {
			for(String id:userIds) {
				if(id.equals(purchaseOrderBean.getCreateUser())) { 
					isStatus = 1;
					break;
				} 
			}
		}
		Assert.isTrue(isStatus==1, "暂无权限审核此采购单");
		if(status == 2) {//退回
			//校验采购单能否直接退回 库存可用数-（取消订单的采购数-占用数）<0 
			feedOrderService.checkPurchaseOrderApprovalBack(map.get("purchaseDetailId").toString(),Integer.valueOf(type),map.get("loginCompany").toString());
		}
		//如果是订单采购退回,需要特殊处理
		if(status == 2 && type.equals("1")) {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("purchaseOrderBean", purchaseOrderBean);
			paramMap.put("purchaseDetailId", map.get("purchaseDetailId"));
			paramMap.put("loginCompany", map.get("loginCompany"));
			paramMap.put("approvalTime",map.get("approvalTime")); 
			paramMap.put("approvalUser",map.get("loginUserId"));
			paramMap.put("approvalReason",map.get("approvalReason"));
			this.returnPurchaseOrder(paramMap);
		}else {
			if(purchaseOrderBean.getStatus() != 0) {
				throw new ServiceException("该采购单已审核,请勿重复操作");
			}
			int row = purchaseOrderMapper.setPurchaseOrderOnStatus(map);
			this.isSuccess(row,"审核失败");
		}
		String message = workshopService.sendApprovalStatusMassage(status, userBean.getId(), map.get("loginUserName").toString(), "采购单", RedirectUrlUtil.queryPurchaseOrder);
		return "操作成功 "+message;
	}
	
	/**
	 * 批量审核采购单
	* @date 2018年10月10日 下午2:16:51 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String approvalAllPurchaseOrder(Map<String, Object> map, int status) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("approvalTime",simpleDateFormat.format(new Date())); 
		map.put("approvalUser",map.get("loginUserId"));
		String [] ids = map.get("ids").toString().split(","); 
		map.put("ids", ids);
		Map<String,Object> approvalParam = new HashMap<String,Object>();
		approvalParam.put("type","4"); 
		approvalParam.put("loginUserId", map.get("loginUserId"));
		approvalParam.put("loginCompany", map.get("loginCompany"));
		List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
		List<UserBean> createUserlist = purchaseOrderMapper.getPurchaseOrderCreateUserIdsByPurchaseDetailList(map);
		for(UserBean createUser:createUserlist) {
			Assert.isTrue(userIds.contains(createUser.getId()),"审核失败,暂无权限审核"+createUser.getUserName()+"制的采购单");
		}
		int row = purchaseOrderMapper.setAllPurchaseOrderOnStatus(map);
		Assert.isTrue(row>0, "审核成功");
		StringBuffer sb = new StringBuffer();
		for(UserBean userBean:createUserlist) { 
			String message = workshopService.sendApprovalStatusMassage(1, userBean.getId(), map.get("loginUserName").toString(), "采购单审批通知", RedirectUrlUtil.queryPurchaseOrder);
			if(!message.isEmpty()) {
				sb.append(message);
				break;
			}
		} 
		return sb.toString();
	}
	
	/**
	 * 退回订单采购单
	* @date 2018年9月14日 上午9:09:14 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public void returnPurchaseOrder(Map<String,Object> map) {
		PurchaseOrderBean purchaseOrderBean = (PurchaseOrderBean) map.get("purchaseOrderBean");
		if(purchaseOrderBean.getStatus().equals(1)) {   
			int isRetreatStatus = this.isRetreatPurchaseOrder(map);
			if(isRetreatStatus==2) { 
				throw new ServiceException("无需退回");
			}
		}
		map.put("feedDetailId", purchaseOrderBean.getFeedDetailId());
		FeedOrderDetailBean feedOrderDetailBean =  feedUseMaterialCountMapper.getFeedOrderDetailById(map).get(0);
		Assert.notNull(feedOrderDetailBean, "投料单明细为空");
		//Assert.isTrue("1".equals(feedOrderDetailBean.getStatus()), "该投料单已经退回,请勿重复操作");
		if("1".equals(feedOrderDetailBean.getStatus())) {//有投料单未退回则退回
			orderService.isCheckReturnFeedOrderHaveWarehouseOut(map);
			List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(map);
			//当有占用数时
			if(feedUseMaterialCountBeans !=null && feedUseMaterialCountBeans.size()>0) {
				 int feedUseRow = feedUseMaterialCountMapper.deleteFeedUseMaterialById(feedUseMaterialCountBeans.get(0));
				 Assert.isTrue(feedUseRow>0, "消除投料单占用数异常");
			}
			//退回投料单 
			int feedRow = orderMapper.updateFeedDetailToUnreviewed(map);
			Assert.isTrue(feedRow>0, "投料单退回异常");
		}
		boolean isInCount = this.isPurchaseOrderInCount(purchaseOrderBean,map);
		//未入库
		if(!isInCount) {
			Map<String,String> purchaseMap = new HashMap<String,String>();
			purchaseMap.put("status","2");
			purchaseMap.put("type", "1");
			purchaseMap.put("loginCompany", map.get("loginCompany").toString());
			purchaseMap.put("purchaseDetailId", purchaseOrderBean.getPurchaseDetailId());
			purchaseMap.put("approvalTime", map.get("approvalTime").toString());
			purchaseMap.put("approvalUser", map.get("approvalUser").toString());
			purchaseMap.put("approvalReason", map.get("approvalReason").toString());
			int row = purchaseOrderMapper.setPurchaseOrderOnStatus(purchaseMap);
			Assert.isTrue(row>0, "采购单退回异常");
		}
	}
	
	
	/**
	 * 发送采购价格异常信息
	* @date 2018年9月13日 下午1:39:44 
	* @author 李斌
	* @return void 
	* @throws
	 */
	private void getSendData(Map<String,Object> map ) {
		//物料信息 
		List<CompanyMaterialTableBean> companyMaterialTableBeans =  (List<CompanyMaterialTableBean>) map.get("companyMaterialTableBeanList");
		//采购单
		List<PurchaseOrderBean> purchaseDetailBeanList = (List<PurchaseOrderBean>) map.get("purchaseOrderBeanList");
		//采购单ids
		List<String> mainList = (List<String>) map.get("mainList");
		String date = map.get("date").toString();
		for(PurchaseOrderBean purchaseDetailBean:purchaseDetailBeanList) {
			if(purchaseDetailBean.getPrice()==null) {
				continue;
			}
			for(CompanyMaterialTableBean companyMaterialTableBean:companyMaterialTableBeans) {
				if(companyMaterialTableBean.getUnitPrice()==null) {
					continue;
				}
				if(purchaseDetailBean.getMaterialCode().equals(companyMaterialTableBean.getMaterialCode())) {
					if(companyMaterialTableBean.getUnitPrice().doubleValue()>=purchaseDetailBean.getPrice().doubleValue()) {
						return;
					}
					//溢出金额
					BigDecimal overFlowMoney = null;
					//物料单价
					Double unitPrice = companyMaterialTableBean.getUnitPrice();
					BigDecimal materialMoney = null;
					if(unitPrice==null) {
						materialMoney = new BigDecimal("0.0");
					}else {
						materialMoney = new BigDecimal(unitPrice.toString());
					}
					//采购单价 
					BigDecimal purchasePrice = new BigDecimal(purchaseDetailBean.getPrice().toString());
					if(materialMoney.doubleValue()>0) {
						overFlowMoney =purchasePrice.subtract(materialMoney).divide(materialMoney, 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal("100"));
					}else {
						overFlowMoney =purchasePrice.subtract(materialMoney).divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal("100"));
					}
					
					String bodyMessage = "该订单采购单的物料采购单价,高出物料表中物料单价的"+(overFlowMoney)+"%";
					Map<String, Object> purchaseUnitPriceMap = new HashMap<String,Object>();
					purchaseUnitPriceMap.put("loginCompany", map.get("loginCompany"));
					String idString = mainList.toString().substring(1,mainList.toString().length()-1);
					String queryCondition = "#type=1&mainId="+idString.replace(" ","");  
					String pageType = RedirectUrlUtil.queryPurchaseOrder+queryCondition;
					orderService.sendUnitPriceAnomaliesMsg("订单采购单价异常", bodyMessage, date, purchaseUnitPriceMap, pageType);
				}
			}
		}
	}
	
	/**
	 * 校验物料
	* @date 2018年9月13日 下午1:41:08 
	* @author 李斌
	* @return int 
	* @throws
	 */
	public int isCheckMateiral(CompanyMaterialTableBean companyMaterialTableBean) {
		if(companyMaterialTableBean!=null) {
			if("禁用".equals(companyMaterialTableBean.getStatus())) {
				throw new ServiceException("该物料被禁用,生成采购单失败");
			} 
			if(!"原材料仓".equals(companyMaterialTableBean.getDefaultWarehouse()) && !"辅料仓".equals(companyMaterialTableBean.getDefaultWarehouse())) {
				throw new ServiceException("该物料非原材料仓与辅料仓,生成采购单失败");
			}
			return companyMaterialTableBean.getProcurementCycles()==null?0:companyMaterialTableBean.getProcurementCycles(); 
		}else{
			throw new ServiceException("物料信息为空异常");
		}
	}

	
	/**
	 * 检验数据影响行
	* @date 2018年9月14日 上午9:05:38 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public void isSuccess(int row,String message) {
		if(row <1) {
			throw new ServiceException(message);
		}
	}
	
	/**
	 * 校验采购单是否可被退回
	* @date 2018年7月26日 上午9:38:28 
	* @author 李斌
	* @return boolean 
	* @throws
	 */ 
	public int isRetreatPurchaseOrder(Map<String,Object> map) {
		// 返回1 说明 需退回投料单 返回2 无需退回投料单
		//获取采购单
		PurchaseOrderBean purchaseOrderBean = (PurchaseOrderBean) map.get("purchaseOrderBean");
		if(purchaseOrderBean==null) {
			throw new ServiceException("订单采购单为空异常");
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("loginCompany", map.get("loginCompany"));
		//获取修改记录applyId
		paramMap.put("orderId", purchaseOrderBean.getOrderId());
		String applyId = orderMapper.getApplyIdByOrderId(paramMap);
		//获取订单修改记录信息与原纪录
		paramMap.put("applyId", applyId);
		paramMap.put("lineNo", purchaseOrderBean.getLineNo());
		paramMap.put("materialFactory", purchaseOrderBean.getMaterialFactory());
		paramMap.put("materialType", purchaseOrderBean.getMaterialType());
		List<OrderInfoDetailSourceAndApplyBean> orderList = orderMapper.getOrderInfoDetailSourceAndApply(paramMap);
		if(orderList==null || orderList.size()<1) {
			throw new ServiceException("无订单修改记录异常");
		}
		for(OrderInfoDetailSourceAndApplyBean order:orderList) {
			//原订单投料数
			BigDecimal feedTotal = new BigDecimal(order.getFeedTotal());
			//修改后的订单投料数
			BigDecimal applyFeedTotal = new BigDecimal(order.getApplyFeedTotal());
			ReportBean reportBean = new ReportBean();
			reportBean.setOrderId(order.getOrderNo());//订单编号
			reportBean.setMachining(order.getMaterialType());//物料类型
			reportBean.setRowIndex(order.getLineNo());//行号
			//判断物料是否修改过
			long count = workshopService.getOrderAllWorkShopTurnoverCount(reportBean);
			if(!order.getApplyColor().equals(order.getColor()) 
					|| !order.getApplyColorDescription().equals(order.getColorDescription()) 
					|| !order.getApplyMaterialModel().equals(order.getMaterialModel())) {
				//得到在车间的数量
				//判断车间物料是否全部退回
				if(count != 0) {
					//String msg ="请先检查订单号["+order.getOrderNo()+"]序号["+order.getLineNo()+"]物料["+order.getMaterialType()+"]还需退回仓库["+count+"付]\r\n";
					//throw new ServiceException(msg);
				}
				return 1;
			}
			if(!order.getMaterialCode().equals(order.getApplyMaterialCode())) {
				//得到在车间的数量
				//判断车间物料是否全部退回
				if(count != 0) {
					//String msg ="请先检查订单号["+order.getOrderNo()+"]序号["+order.getLineNo()+"]物料["+order.getMaterialType()+"]还需退回仓库["+count+"付]\r\n";
					//throw new ServiceException(msg);
				}
				return 1;
			}
			FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(purchaseOrderBean.getFeedDetailId());
			//如果订单投料数改小 
			if(feedTotal.subtract(applyFeedTotal).doubleValue()>0) {
				//调用校验方法
				paramMap.put("feedDetailId",purchaseOrderBean.getFeedDetailId());
				paramMap.put("oldFeedTotal", feedTotal);
				paramMap.put("newFeedTotal", applyFeedTotal);
				paramMap.put("materialCode", order.getMaterialCode());
				//退回到仓库的物料(付)
				Double returnToWarehouseCount = warehouseService.returnToMaterialByFeed(paramMap);
				//说明料没有领出去
				if(feedOrderDetailBean.getReceiveCount().doubleValue()==0 && feedOrderDetailBean.getProductionUnitReceiveCount()==0) {
					return 1;
				}
				//如果退回到仓库的数量大于等于原订单投料数-申请修改的订单投料数 那么就退回投料单
				if(returnToWarehouseCount.doubleValue()>=(feedTotal.subtract(applyFeedTotal).doubleValue())) {
					return 1; 
				}else {
					//String msg ="请先检查订单号["+order.getOrderNo()+"]序号["+order.getLineNo()+"]物料["+order.getMaterialType()+"]还需退回仓库["+(feedTotal.subtract(applyFeedTotal).doubleValue()-returnToWarehouseCount.doubleValue())+"付]\r\n";
					//throw new ServiceException(msg);
					return 1;
				}
			}else if(feedTotal.subtract(applyFeedTotal).doubleValue()<0){ 
				return 1;
			}
			//如果用料条数改变了
//			if(!order.getYltsTotal().equals(order.getApplyYltsTotal())) {
//				//订单原用料条数
//				BigDecimal yltsTotal = new BigDecimal(order.getYltsTotal());
//				//修改后的用料条数
//				BigDecimal applyYltsTotal = new BigDecimal(order.getApplyYltsTotal());
//				//原本就没有用料条数
//				if(yltsTotal.doubleValue()==0) {
//					return 1;
//				} 
//				if(yltsTotal.subtract(applyYltsTotal).doubleValue()>0) {//改小
//					//说明料没有领出去
//					if(feedOrderDetailBean.getReceiveCount().doubleValue()==0 && feedOrderDetailBean.getProductionUnitReceiveCount()==0) {
//						return 1;
//					}
//					double returnFuCount = 0;
//					if(feedOrderDetailBean.getFeedCount().doubleValue()==0) {
//						returnFuCount = yltsTotal.divide(feedTotal, BigDecimal.ROUND_HALF_UP,2).multiply(yltsTotal.subtract(applyYltsTotal)).doubleValue();
//					}else {
//						BigDecimal feedCount = new BigDecimal(feedOrderDetailBean.getFeedCount().toString());
//						returnFuCount = yltsTotal.divide(feedCount, BigDecimal.ROUND_HALF_UP,2).multiply(yltsTotal.subtract(applyYltsTotal)).doubleValue();
//					}
//					String msg ="请先检查订单号["+order.getOrderNo()+"]序号["+order.getLineNo()+"]物料["+order.getMaterialType()+"]还需退回仓库["+returnFuCount+"付或"+yltsTotal.subtract(applyYltsTotal)+order.getYltsUnit()+"]\r\n";
//					throw new ServiceException(msg);
//				}else if(yltsTotal.subtract(applyYltsTotal).doubleValue()<0) {//改大
//					return 1;
//				}
//			}
			//如果用料条数改变了
			if(!order.getYltsTotal().equals(order.getApplyYltsTotal())) {
				return 1;
			}
			return 2;
		}
		return 0;
	}
	
	/**
	 * 传入参数 采购单投料单对应表对象,Map(内有公司名)
	 * 订单采购单是否入库 
	* @date 2018年8月9日 上午7:54:17 
	* @author 李斌
	* @return boolean 
	* @throws 
	 */
	public boolean isPurchaseOrderInCount(PurchaseOrderBean purchaseOrderBean,Map<String,Object> map) {
		//如果采购单未审核,肯定没入库
		if(purchaseOrderBean.getStatus()==0) {
			return false;
		}
		//通过采购单对应表id查询原料仓出入库明细与其他仓位出入库明细
		Map<String,Object> purchaseMap = new HashMap<String,Object>();
		purchaseMap.put("loginCompany", map.get("loginCompany"));
		purchaseMap.put("purchaseOrderId", purchaseOrderBean.getPurchaseDetailId());
		List<WarehouseInOutDetailBean> warehouseInOutDetailBeans = purchaseOrderMapper.getWarehouseInOutByPurchaseDetailId(purchaseMap);
		//如果没有入库记录,那么说明该采购单没有入库
		if(warehouseInOutDetailBeans !=null && warehouseInOutDetailBeans.size()>0) {
			Assert.isTrue(purchaseOrderBean.getInCount().doubleValue()!=0, "该采购单有入库记录未审核,请先审核");
			return true;
		}
		return false;
	}
	
	/**
	 * 获取未入库完成的采购单
	* @date 2018年9月14日 下午3:49:39 
	* @author 李斌
	* @return DatatablesViewPageBean<CompanyMaterialTableBean> 
	* @throws
	 */
	public DatatablesViewPageBean<CompanyMaterialTableBean> getPurchaseOrderOnPurchaseWarehouseIn(
			Map<String, Object> map) {
		CompanyBean companyBean = companyMapper.getCompany(map);
		List<CompanyMaterialTableBean> companyMaterialTableBeans = purchaseOrderMapper.getPurchaseOrderOnPurchaseWarehouseInData(map);
		
		//获取公司物料仓位，一个物料有多个
		List<MaterialPositionBean> materialPositionList = companyMaterialCountService.getMaterialPositionList(map);
		Set<String>  provideNameSet=companyMaterialTableBeans.stream().map(CompanyMaterialTableBean::getProviderName).collect(Collectors.toSet());
		List<CustomerBean> customerBeans=purchaseOrderMapper.getSubCustomByCompanyAndParentName(provideNameSet,companyBean.getCompanyName());
		
		for(CompanyMaterialTableBean companyMaterialCount:companyMaterialTableBeans) {
			//设置物料仓位
			List<String> positionList = materialPositionList.stream().filter(po->po.getMaterialCode().equals(companyMaterialCount.getMaterialCode())).map(MaterialPositionBean::getPosition).collect(Collectors.toList());
			companyMaterialCount.setPositionList(positionList);
			companyMaterialCount.setSubProviderSet(customerBeans.stream().filter(cc->cc.getParentName().equals(companyMaterialCount.getProviderName())).map(CustomerBean::getCustomerName).collect(Collectors.toSet()));
		}
		int count = purchaseOrderMapper.getPurchaseOrderOnPurchaseWarehouseInCount(map);
		DatatablesViewPageBean<CompanyMaterialTableBean> datatablesViewPageBean = new DatatablesViewPageBean<CompanyMaterialTableBean>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(companyMaterialTableBeans);
		datatablesViewPageBean.setCode(companyBean.getCanUpdatePriceAndUnit());
		return datatablesViewPageBean;
	}
	
	/**
	 * 更新采购单复期,通过明细id
	* @date 2018年10月4日 下午4:23:06 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	public void updatePurchaseLaterPhaseByPurchaseDetailId(Map<String, Object> map) {
		Assert.notNull(map.get("purchaseDetailId"), "采购单明细Id为空");
		Assert.notNull(map.get("loginCompany"), "公司名为空");
		int row = purchaseOrderMapper.updatePurchaseLaterPhaseByPurchaseDetailId(map);
		Assert.isTrue(row>0,"修改复期失败");
	}

	public DatatablesViewPageBean<PurchaseOrderDetailPojo> getPurchaseOrderOnWeChat(Map<String, Object> map) {
		Assert.notNull(map.get("mainId"), "mainId为空");
		String idsStr = map.get("mainId").toString();
		String[] ids = idsStr.split(",");
		map.put("mainId", ids);
		Map<String,Object> approvalParam = new HashMap<String,Object>();
		approvalParam.put("type","4"); 
		approvalParam.put("id",map.get("loginUserId"));  
		approvalParam.put("loginCompany", map.get("loginCompany"));
		//获取当前登录人可以审核的人员
		List<String> userIds = approvalMapper.getHaveId(approvalParam);
		//公司设定
		CompanyBean companyBean = companyMapper.getCompany(map);
		
		List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
		map.put("nopage", "nopage");
		int count = purchaseOrderMapper.getPurchaseOrderByPageCount(map);
		
		//所有客户 
		map.remove("type");
		List<CustomerBean> customerBeans = basicDataMapper.queryCustomers(map);
		for(PurchaseOrderDetailPojo pojo:pojos) {
			for(CustomerBean customerBean:customerBeans) {
				if(pojo.getProviderName().equals(customerBean.getCustomerName())) {
					pojo.setCustomerBean(customerBean);
					break;
				}
			}	
			for(String userId:userIds) {
				if(userId.equals(pojo.getCreateUserId())) {
					pojo.setIsApprovalUser(1);
					break; 
				}
			} 
			pojo.setPrintNeetApproval(companyBean.getPurchasePrintIsNeetApproval());
		} 
		DatatablesViewPageBean<PurchaseOrderDetailPojo> datatablesViewPageBean = new DatatablesViewPageBean<PurchaseOrderDetailPojo>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(pojos);
		return datatablesViewPageBean;
	}
	
	/**
	 * 发送采购打印信息到Email
	* @date 2018年10月10日 上午10:12:15 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public void sendEmailOnPurchasePrint(Map<String, String> map) {
		Assert.notNull(map.get("providerName"),"供应商名称为空");
		Assert.notNull(map.get("printHtml"), "打印发送信息为空");
		List<String> toAddrs = new ArrayList<String>();
		map.put("customerName", map.get("providerName"));
		List<CustomerBean> customerList = basicDataMapper.queryCustomers(map);
		map.put("status","使用");
		List<CustomerBean> checkCustomerList = basicDataMapper.queryCustomers(map);
		if(checkCustomerList.size()>0) {
			if(!"".equals(checkCustomerList.get(0).getEmail().trim())) {
				toAddrs.add(checkCustomerList.get(0).getEmail());
			}
		}else {
			for(CustomerBean customerBean:customerList) {
				if(!"".equals(customerBean.getEmail().trim())) {
					toAddrs.add(customerBean.getEmail().trim());
					break;
				}
			}
		}
		Assert.isTrue(toAddrs.size()>0, "供应商的邮箱为空");
		String printHtml = map.get("printHtml");
		try {
			companyEmailService.companyMailSend(toAddrs.toArray(new String[toAddrs.size()]),new String[0] , "采购单打印信息", printHtml,map.get("loginCompany").toString(), 1,map.get("fileName"),map.get("remoteUrl"));
		} catch (Exception e) {
			System.out.println(e.getMessage());
			Assert.notNull(null, "发送信息失败 "+e.getMessage());
		}
	}
	
	/**
	 * 获取拖期信息
	* @date 2018年10月24日 上午11:15:01 
	* @author 李斌
	* @return List<PurchaseOrderDetailPojo> 
	* @throws
	 */
	public List<PurchaseOrderDetailPojo> getPurchaseOrderListOnJobSendMsg(Map<String, Object> map) {
		Assert.notNull(map.get("status"), "状态为空");
		Assert.notNull(map.get("type"),"采购类型为空");
		Assert.notNull(map.get("tardinessMax"), "拖期最大值为空");
		Map<String,Object> approvalParam = new HashMap<String,Object>();
		approvalParam.put("type","4"); 
		approvalParam.put("id",map.get("loginUserId"));  
		approvalParam.put("loginCompany", map.get("loginCompany"));
		//获取当前登录人可以审核的人员
		List<String> userIds = approvalMapper.getHaveId(approvalParam);
		List<PurchaseOrderDetailPojo> pojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
		for(PurchaseOrderDetailPojo pojo:pojos) {
			for(String userId:userIds) {
				if(userId.equals(pojo.getCreateUserId())) {
					pojo.setIsApprovalUser(1);
					break; 
				}
			}
		}
		return pojos;
	}
	
	/**
	 * 获取投料单生成采购单后,可占用物料数量
	 * @param company
	 * @param materialCode
	 * @return
	 */
	public double getReceiveCountByFeedCount(String company,String materialCode) {
		//库存可用数 = 仓库数量+采购未入库数量-投料单关联数量
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("materialCode", materialCode);
		paramMap.put("loginCompany", company);
		double receiveCount = purchaseOrderMapper.getReceiveCountByFeedCount(paramMap);
		return receiveCount;
	}
	
	/**
	 * 添加采购打印id与采购单号
	 * @param map
	 */
	public void addPurchasePrint(Map<String, Object> map) {
		List<String>purchaseDetailList = this.getPurchaseDetailIdByPtId(map);
		String [] ids = map.get("ids").toString().split(",");
		Assert.isTrue(purchaseDetailList.size()!=ids.length, "采购号已存在");
		purchaseOrderMapper.addPurchasePrint(map);
	} 
	
	public List<String> getPurchaseDetailIdByPtId(Map<String,Object> map){
		Assert.notNull(map.get("ptId"), "采购号为空");
		return purchaseOrderMapper.getPurchaseDetailIdByPtId(map);
	}

	public PurchasePrintBean getPurchaseNoByProviderNameAndPurchaseDetailIds(Map<String, Object> map) {
		Assert.notNull(map.get("providerName"), "供应商名称为空");
		Assert.notNull(map.get("ids"), "采购ids为空");
		PurchasePrintBean purchasePrint = new PurchasePrintBean();
		//先查询是否有相同的,如果有就用以前的,如果没有,就新建一个
		String [] ids = map.get("ids").toString().split(",");
		map.put("purchaseDetailIds",ids);
		List<PurchasePrintBean> purchasePrintList = purchaseOrderMapper.getPurchaseNoByPurchaseDetailIds(map);
		if(purchasePrintList ==null || purchasePrintList.size()<1) {
			String providerName = map.get("providerName").toString();
			String ptId = dingTalkMapper.getApprovalNo("PT");
			String purchaseNo = BasicDataService.getPYIndexStr(providerName, true)+ptId.substring(2,ptId.length());
			purchasePrint.setPurchaseNo(purchaseNo);
			purchasePrint.setExist(false);
		}else {
			for(PurchasePrintBean purchasePrintBean:purchasePrintList) {
				if(purchasePrintBean.getPurchaseDetailSize().equals(ids.length)) {
					purchasePrint.setPurchaseNo(purchasePrintBean.getPurchaseNo());
					purchasePrint.setExist(true);
					break;
				}else {
					String providerName = map.get("providerName").toString();
					String ptId = dingTalkMapper.getApprovalNo("PT");
					String purchaseNo = BasicDataService.getPYIndexStr(providerName, true)+ptId.substring(2,ptId.length());
					purchasePrint.setPurchaseNo(purchaseNo);
					purchasePrint.setExist(false);
					break;
				}
			}
		}
		return purchasePrint;
	}
	
	public Set<String> getPurchaseNoList(Map<String, Object> map) {
		return purchaseOrderMapper.getPurchaseNoList(map);
	}
	
	/**
	 * 获取某物料的可用数
	 * @param materialCode
	 * @param company
	 * @return
	 */
	public Double getMaterialAvailableCount(String materialCode,String loginCompany) {
		//物料可用数 = 库存数 + 采购未入库数 - 投料单未领料数 
		Map<String,Double> availableCountMap =  purchaseOrderMapper.getMaterialAvailableCount(materialCode,loginCompany);
		//库存数
		BigDecimal bigStockCount = new BigDecimal(availableCountMap.get("stockCount").toString());
		//采购未入库数
		BigDecimal bigNotInCount = new BigDecimal(availableCountMap.get("notInCount").toString());
		//投料单未领料数
		BigDecimal bigNotReceiveCount = new BigDecimal(availableCountMap.get("notReceiveCount").toString());
		//物料未审核
		//得到未审核数量
		Map calWorkShopCount = new HashMap<>();
		calWorkShopCount.put("materialCode", materialCode);
		calWorkShopCount.put("loginCompany",loginCompany);
		Double usePurchseNotApprovelCount = 0.0;
		List<OrderReceiveViewBean> mateiralNotApprovalCountList = issueNoteService.getMaterialNotApprovalCount(calWorkShopCount);
		if(mateiralNotApprovalCountList.size()>0) {
			usePurchseNotApprovelCount=mateiralNotApprovalCountList.get(0).getNotApprovelCount();
		}
		double materialAvailableCount = bigStockCount.add(bigNotInCount).subtract(bigNotReceiveCount).add(BigDecimal.valueOf(usePurchseNotApprovelCount)).doubleValue();
		return materialAvailableCount<0?0:materialAvailableCount;
	}
	
	/**
	 * 获取某物料的占用数
	 * @return
	 */
	public Double getMaterialUseCount(String materialCode,String loginCompany) {
		//物料可用数 = 库存数 + 采购未入库数 - 投料单未领料数 - 返料单未返料数
		Map<String,Double> availableCountMap =  purchaseOrderMapper.getMaterialAvailableCount(materialCode,loginCompany);
		//投料单未领料数
		BigDecimal bigNotReceiveCount = new BigDecimal(availableCountMap.get("notReceiveCount").toString());
		return bigNotReceiveCount.doubleValue();
	}
	
	/**
	 * 获取占用物料的订单(也就是关联的订单)
	 * @return
	 */
	public List<AvailableCountPojo> getMaterialUseCountByFeed(String materialCode,String loginCompany){
		List<AvailableCountPojo> dataList = purchaseOrderMapper.getMaterialUseCountByFeedData(materialCode,loginCompany);
		return dataList;
	}
	
	
}
